'use strict';

const { Products,Op } = require('../model');
const { is } = require('koa/lib/response');

let fn_Product_List = async(ctx,next)=>{
    let keyword = ctx.request.query.keyword || '';
    if(keyword){
        ctx.body = await Products.findAll({
            where:{
                [Op.or]:[
                    {id:isNaN(keyword)?0:parseInt(keyword)},
                    {title:keyword},
                    {digest:keyword},
                    {content:keyword},
                    {type:keyword},
                    {author:keyword},
                    {time:keyword}
                ]
            },
            order:['id']
        })
    }else{
        ctx.body = await Products.findAll({
            order:['id']
        })
    }
}

let fn_product_id = async(ctx,next)=>{
    let id = ctx.request.params.id;
    if(id){
        ctx.body= await Products.findAll({
            where:{
                id:id
            }
        })
    }else{
        ctx.body={
            code:400,
            data:'',
            msg:'获取失败'
        }
    }
}

let fn_post = async(ctx,next)=>{
    let obj = ctx.request.body;
    if(obj.title){
        let list = {
            title:obj.title,
            digest:obj.digest,
            content:obj.content,
            type:obj.type,
            author:obj.author,
            time:obj.time
        }
        await Products.create(list);
        ctx.body={
            code:1000,
            data:list[0],
            msg:'添加成功'
        }
    }else{
        ctx.body={
            code:400,
            data:'',
            msg:'添加失败'
        }
    }
}

let fn_put = async(ctx,next)=>{
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    let list = await Products.findByPk(id);
    if(list){
        await Products.update(obj,{
            where:{
                id:obj.id
            }
        })
        ctx.body={
            code:1000,
            data:'',
            msg:'编辑成功'
        }
    }else{
        ctx.body={
            code:400,
            data:'',
            msg:'编辑失败'
        }
    }
}

let fn_delete = async(ctx,next)=>{
    let id = ctx.request.params.id;
    let list = await Products.findByPk(id);
    if(list){
        await Products.destroy({
            where:{
                id:id
            }
        })
        ctx.body={
            code:1000,
            data:'',
            msg:'删除成功'
        }
    }else{
        ctx.body={
            code:400,
            data:'',
            msg:'删除失败'
        }
    }
}

module.exports={
    'get /product':fn_Product_List,
    'get /product/:id':fn_product_id,
    'post /product':fn_post,
    'put /product/:id':fn_put,
    'delete /product/:id':fn_delete
}